package com.example.librarysystem.Service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.sql.Date;

@Component
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendReturnMail(String to, Date date, String bookName, String borrowerNme) throws MailException {
        SimpleMailMessage message = new SimpleMailMessage();
        String content = "尊敬的" +borrowerNme+ "，您借阅的书《"+bookName+"》于"+date.toString()+"到期，请及时归还，以免影响您的信用";
        message.setFrom(from); // 邮件发送者
        message.setTo(to); // 邮件接受者
        message.setSubject("图书催还通知"); // 主题
        message.setText(content); // 内容
        mailSender.send(message);
    }

    @Override
    public void sendOrderMail(String to, Date start, Date end, String bookName,String borrowerNme){
        SimpleMailMessage message = new SimpleMailMessage();
        String content = "尊敬的" +borrowerNme+ "，您预约了"+start.toString()+"到"+end.toString()+"的书《"+bookName+"》，记得取书哦！";
        message.setFrom(from); // 邮件发送者
        message.setTo(to); // 邮件接受者
        message.setSubject("图书预约通知"); // 主题
        message.setText(content); // 内容
        System.out.println("send1");
        mailSender.send(message);
        System.out.println("send2");
    }

    @Override
    public void sendOverMail(String to, Date end, String bookName, String borrowerNme){
        SimpleMailMessage message = new SimpleMailMessage();
        String content = "尊敬的" +borrowerNme+ "，您借阅的书《"+bookName+"》，已于" + end.toString() + "到期，若超过5天不归还，您的账户将被冻结";
        message.setFrom(from); // 邮件发送者
        message.setTo(to); // 邮件接受者
        message.setSubject("图书到期通知"); // 主题
        message.setText(content); // 内容
        mailSender.send(message);
    }

    @Override
    public void sendBanMail(String to, Date start, Date end, String bookName, String borrowerNme, int type){
        SimpleMailMessage message = new SimpleMailMessage();
        String content = null;
        if(type == 0){
            content = "尊敬的" +borrowerNme+ "，您借阅的书《"+bookName+"》，已于" + end.toString() +
                    "到期超过5天不归还，您的账户将已经冻结，从即日起冻结期15天，特此通知。";
        }else {
            content = "尊敬的" +borrowerNme+ "，您预约的书《"+bookName+"》，已于" + end.toString() +
                    "到期，您在此期间未进行借阅，因此您的账户将已经冻结，从即日起冻结期15天，特此通知。";
        }
        message.setFrom(from); // 邮件发送者
        message.setTo(to); // 邮件接受者
        message.setSubject("账号封禁通知"); // 主题
        message.setText(content); // 内容
        mailSender.send(message);
    }
}

